package com.example.demo.controller;

import com.example.demo.model.Response;
import com.example.demo.model.User;
import com.example.demo.service.UserService;
import com.example.demo.util.JWTUtil;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Optional;

/**
 * @author Eric Wu
 * @since 1.8
 * create 2020-06-08
 */
@Slf4j
@RestController
@RequestMapping("/user")
public class WebController {

    @Autowired
    private UserService userService;

    @Autowired
    private JWTUtil jwtUtil;


    @GetMapping("/all/{page}/{pageSize}")
    public Response<PageInfo<User>> queryAllUser(@PathVariable("page") Integer page,
                                           @PathVariable("pageSize") Integer pageSize) {
        PageInfo<User> result = userService.queryAllUser(page, pageSize);
        return Response.createOkResponse(result);
    }

    @GetMapping("/info/{name}/{password}")
    public Response<String> queryUserByName(@PathVariable("name") String name,@PathVariable("password") String password){

        Optional<User> userOption = userService.queryUserByName(name);
        if(userOption.isEmpty()){
            return Response.createErrorResponse("no the user name");
        }
        return Response.createOkResponse(jwtUtil.sign(userOption.get().getName(),userOption.get().getPassword()));
    }

}
